package com.css.datasourceSwitch;


import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.css.datasourceSwitch.entity.ProvinceDsEntity;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author liusl
 * @description:
 * @date 2024/9/12 下午5:25
 */
//@Aspect
//@Component
//@Order(1)
@Slf4j
public class ProvinceDataSourceAspect {

    @Resource
    //DbForUserService dbForUserService;

    // 定义切点，拦截带有 @ProvinceDS 注解的方法
    @Pointcut("@annotation(com.css.datasourceSwitch.entity.ProvinceDS) || @within(com.css.datasourceSwitch.entity.ProvinceDS)")
    public void provinceDataSourcePointCut() {}

    @Around("provinceDataSourcePointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        String dataSourceKey = "";
        // 获取当前方法的参数
        Object[] args = point.getArgs();
        if(args != null && args.length>0){
            //  省份取第一个参数
            Object firstArg = args[0];
            if (firstArg instanceof ProvinceDsEntity) {
                ProvinceDsEntity proEnty = (ProvinceDsEntity) firstArg;
                dataSourceKey = ProvinceDsUtil.getDataSourceKey(proEnty.getProvinceId());
            }
        }
        if(dataSourceKey == null || dataSourceKey.isEmpty()){
            dataSourceKey = getProvinceDefaultDataSource();
        }
        log.debug("切换数据源："+dataSourceKey);
        try {
            // 切换到对应省份的数据源
            if (dataSourceKey != null && !dataSourceKey.isEmpty()) {
                DynamicDataSourceContextHolder.push(dataSourceKey);  // 切换到省份数据源
            }
            return point.proceed();  // 执行原方法
        } finally {
            log.debug("清除数据源");
            // 清除数据源，回到默认数据源
            DynamicDataSourceContextHolder.clear();
        }
    }

    private String getProvinceDefaultDataSource(){
//        return dbForUserService.getCurrentUserProvince();
        return null;
    }

    // 数据源切换逻辑，假设这里根据 provinceId 切换数据源
    private void switchDataSource(Long provinceId) {
        String dataSourceKey = ProvinceDsUtil.getDataSourceKey(provinceId);
        DynamicDataSourceContextHolder.push(dataSourceKey);
    }

    // 恢复默认数据源
    private void restoreDefaultDataSource() {
        DynamicDataSourceContextHolder.clear();
    }
}
